package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

// gin 参数绑定 基于请求Content-Type 识别

type LoginForm struct {
	User     string `form:"user" json:"user,omitempty" binding:"required"`
	Password string `form:"password" json:"password,omitempty" binding:"required"`
}

func ParseQueryParams(r gin.IRouter) {
	r.GET("queryString", func(c *gin.Context) {
		username := c.DefaultQuery("username", "alice")
		address := c.Query("address")
		c.JSON(http.StatusOK, gin.H{
			"username": username,
			"address":  address,
		})
	})

	r.POST("/user/search", func(c *gin.Context) {
		// post 参数
		username := c.PostForm("username")
		address := c.DefaultPostForm("address", "usa")
		c.String(http.StatusOK, fmt.Sprintln(username, address))

		// json 参数, 从 body 中读取字节
		// c.GetRawData()

		// path 参数绑定
		// /user/search/:name/:age
		// c.Param()
	})

	r.POST("/login", func(c *gin.Context) {
		var form LoginForm
		// 基于 Content-Type 识别绑定参数
		if err := c.ShouldBind(&form); err == nil {
			log.Printf("%#v\n", form)
			c.JSON(http.StatusOK, form)
		} else {
			c.JSON(http.StatusBadRequest,
				gin.H{
					"message": http.StatusText(http.StatusBadRequest),
				})
		}
	})
}
